from django.contrib import admin
from django.utils.html import format_html
from django import forms
from .models import NavigationGroup, NavigationLink
import json
import base64
from django.utils.safestring import mark_safe

# 定义更多的图标选项
ICON_CHOICES = [
    ('', '----'),
    ('fas fa-home', '首页'),
    ('fas fa-server', '服务器'),
    ('fas fa-database', '数据库'),
    ('fas fa-cloud', '云服务'),
    ('fas fa-cogs', '设置'),
    ('fas fa-chart-line', '图表'),
    ('fas fa-file-alt', '文档'),
    ('fas fa-code', '代码'),
    ('fas fa-bug', '调试'),
    ('fas fa-terminal', '终端'),
    ('fas fa-globe', '网络'),
    ('fas fa-sitemap', '站点地图'),
    ('fas fa-project-diagram', '项目图'),
    ('fas fa-shield-alt', '安全'),
    ('fas fa-lock', '锁定'),
    ('fas fa-key', '密钥'),
    ('fas fa-user', '用户'),
    ('fas fa-users', '用户组'),
    ('fas fa-user-shield', '管理员'),
    ('fas fa-user-cog', '用户设置'),
    ('fas fa-tools', '工具'),
    ('fas fa-wrench', '扳手'),
    ('fas fa-hammer', '锤子'),
    ('fas fa-screwdriver', '螺丝刀'),
    ('fas fa-box', '盒子'),
    ('fas fa-boxes', '多个盒子'),
    ('fas fa-archive', '档案'),
    ('fas fa-folder', '文件夹'),
    ('fas fa-folder-open', '打开的文件夹'),
    ('fas fa-file', '文件'),
    ('fas fa-file-code', '代码文件'),
    ('fas fa-file-pdf', 'PDF文件'),
    ('fas fa-file-word', 'Word文件'),
    ('fas fa-file-excel', 'Excel文件'),
    ('fas fa-file-image', '图片文件'),
    ('fas fa-image', '图片'),
    ('fas fa-video', '视频'),
    ('fas fa-film', '电影'),
    ('fas fa-music', '音乐'),
    ('fas fa-headphones', '耳机'),
    ('fas fa-microphone', '麦克风'),
    ('fas fa-camera', '相机'),
    ('fas fa-laptop', '笔记本电脑'),
    ('fas fa-desktop', '台式电脑'),
    ('fas fa-mobile-alt', '手机'),
    ('fas fa-tablet-alt', '平板'),
    ('fas fa-tv', '电视'),
    ('fas fa-wifi', 'WiFi'),
    ('fas fa-network-wired', '有线网络'),
    ('fas fa-ethernet', '以太网'),
    ('fas fa-hdd', '硬盘'),
    ('fas fa-memory', '内存'),
    ('fas fa-microchip', '芯片'),
    ('fas fa-rocket', '火箭'),
    ('fas fa-robot', '机器人'),
    ('fas fa-brain', '大脑'),
    ('fas fa-lightbulb', '灯泡'),
    ('fas fa-bolt', '闪电'),
    ('fas fa-tachometer-alt', '仪表盘'),
    ('fas fa-search', '搜索'),
    ('fas fa-bell', '通知'),
    ('fas fa-envelope', '邮件'),
    ('fas fa-comment', '评论'),
    ('fas fa-comments', '多条评论'),
    ('fas fa-calendar', '日历'),
    ('fas fa-clock', '时钟'),
    ('fas fa-map-marker-alt', '位置标记'),
    ('fas fa-link', '链接'),
    ('fas fa-external-link-alt', '外部链接'),
    ('fas fa-share-alt', '分享'),
    ('fas fa-sync', '同步'),
    ('fas fa-download', '下载'),
    ('fas fa-upload', '上传'),
    ('fas fa-save', '保存'),
    ('fas fa-print', '打印'),
    ('fab fa-github', 'GitHub'),
    ('fab fa-gitlab', 'GitLab'),
    ('fab fa-docker', 'Docker'),
    ('fab fa-jenkins', 'Jenkins'),
    ('fab fa-jira', 'Jira'),
    ('fab fa-slack', 'Slack'),
    ('fab fa-telegram', 'Telegram'),
    ('fab fa-weixin', '微信'),
    ('fab fa-qq', 'QQ'),
    ('fab fa-alipay', '支付宝'),
]

class NavigationLinkForm(forms.ModelForm):
    """导航链接表单"""
    icon_image_upload = forms.ImageField(
        label='上传图标',
        required=False,
        help_text='支持jpg、png、gif格式的图片'
    )
    
    icon = forms.ChoiceField(
        choices=ICON_CHOICES,
        required=False,
        label='图标',
        help_text='选择一个预设图标或上传自定义图标'
    )

    class Meta:
        model = NavigationLink
        fields = '__all__'
        exclude = ['icon_image_base64', 'icon_image_type']

    def save(self, commit=True):
        # 保存上传的图片到临时字段
        if self.cleaned_data.get('icon_image_upload'):
            self.instance._icon_image_temp = self.cleaned_data['icon_image_upload']
        return super().save(commit)

class NavigationLinkInline(admin.TabularInline):
    """导航链接内联管理"""
    model = NavigationLink
    extra = 1
    form = NavigationLinkForm

class NavigationGroupAdmin(admin.ModelAdmin):
    """导航分组管理"""
    list_display = ('title', 'order', 'created_at')
    search_fields = ('title',)
    ordering = ('order', 'created_at')

class NavigationLinkAdmin(admin.ModelAdmin):
    """导航链接管理"""
    form = NavigationLinkForm
    list_display = ('name', 'url', 'group', 'show_icon', 'order', 'is_active')
    list_filter = ('group', 'is_active')
    search_fields = ('name', 'url', 'description')
    ordering = ('group', 'order', 'created_at')
    list_editable = ('order', 'is_active')
    
    def show_icon(self, obj):
        """显示图标预览"""
        if obj.icon_image_data:
            return format_html('<img src="{}" width="20" height="20" style="object-fit: contain;" />', obj.icon_image_data)
        elif obj.icon:
            return format_html('<i class="{}" style="font-size: 20px;"></i>', obj.icon)
        return '-'
    show_icon.short_description = '图标预览'
    
    def formfield_for_dbfield(self, db_field, **kwargs):
        """自定义表单字段"""
        formfield = super().formfield_for_dbfield(db_field, **kwargs)
        if db_field.name == 'icon':
            formfield.widget = IconSelectWidget(choices=ICON_CHOICES)
        return formfield

    class Media:
        css = {
            'all': (
                '/static/css/fontawesome/all.min.css',
            )
        }
        js = (
            '/static/js/jquery/jquery.min.js',
            '/static/js/fontawesome/all.min.js',
        )

# 自定义图标选择控件
class IconSelectWidget(forms.Select):
    """自定义图标选择控件，带预览功能"""
    template_name = 'admin/icon_select_widget.html'
    
    def render(self, name, value, attrs=None, renderer=None):
        """渲染控件"""
        # 创建原始的select元素（但会被隐藏）
        output = super().render(name, value, attrs, renderer)
        
        # 添加图标预览和搜索功能的HTML和JavaScript
        js = '''
        <style>
            .icon-preview {
                display: inline-block;
                width: 30px;
                text-align: center;
                margin-right: 10px;
                font-size: 18px;
            }
            .icon-select-option {
                display: flex;
                align-items: center;
                padding: 8px;
                cursor: pointer;
                border-bottom: 1px solid #eee;
            }
            .icon-select-option:hover {
                background-color: #f0f0f0;
            }
            .icon-select-container {
                max-height: 300px;
                overflow-y: auto;
                border: 1px solid #ccc;
                margin-top: 5px;
                display: none;
                background-color: white;
                z-index: 1000;
                position: absolute;
                width: 300px;
                box-shadow: 0 4px 8px rgba(0,0,0,0.1);
                border-radius: 4px;
            }
            .icon-search {
                width: 100%;
                padding: 8px;
                margin-bottom: 5px;
                box-sizing: border-box;
                border: none;
                border-bottom: 1px solid #ddd;
            }
            .icon-select-wrapper {
                position: relative;
                margin-bottom: 10px;
            }
            .selected-icon-preview {
                display: inline-block;
                width: 30px;
                text-align: center;
                margin-right: 10px;
                font-size: 20px;
                vertical-align: middle;
            }
            .toggle-icon-select {
                padding: 6px 12px;
                background-color: #f8f9fa;
                border: 1px solid #ddd;
                border-radius: 4px;
                cursor: pointer;
            }
            .toggle-icon-select:hover {
                background-color: #e9ecef;
            }
            .icon-options {
                max-height: 250px;
                overflow-y: auto;
                display: grid;
                grid-template-columns: repeat(4, 1fr);
                gap: 5px;
            }
            .icon-name {
                font-size: 12px;
                color: #666;
                text-align: center;
                word-break: break-word;
                max-width: 100%;
                overflow: hidden;
                text-overflow: ellipsis;
            }
            .icon-grid-item {
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: center;
                padding: 10px 5px;
                border: 1px solid #eee;
                border-radius: 4px;
                cursor: pointer;
                text-align: center;
            }
            .icon-grid-item:hover {
                background-color: #f0f0f0;
                border-color: #ddd;
            }
            .icon-grid-item i {
                font-size: 24px;
                margin-bottom: 5px;
            }
            /* 隐藏原始的select元素 */
            select[name="{1}"] {{
                display: none;
            }}
        </style>
        <div class="icon-select-wrapper">
            <div style="display: flex; align-items: center; margin-bottom: 8px;">
                <div class="selected-icon-preview">
                    <i class="{0}"></i>
                </div>
                <button type="button" class="toggle-icon-select">选择图标</button>
            </div>
            <div class="icon-select-container">
                <input type="text" class="icon-search" placeholder="搜索图标...">
                <div class="icon-options">
                '''.format(value or '', name)
        
        # 添加所有图标选项，以网格形式展示
        for value, label in self.choices:
            if value:  # 跳过空选项
                js += '''
                <div class="icon-grid-item" data-value="{0}" title="{1}">
                    <i class="{0}"></i>
                    <span class="icon-name">{1}</span>
                </div>
                '''.format(value, label)
        
        js += '''
                </div>
            </div>
        </div>
        <script>
            (function($) {
                $(document).ready(function() {
                    // 切换图标选择器显示/隐藏
                    $('.toggle-icon-select').on('click', function() {
                        $(this).closest('.icon-select-wrapper').find('.icon-select-container').toggle();
                        // 聚焦到搜索框
                        $(this).closest('.icon-select-wrapper').find('.icon-search').focus();
                    });
                    
                    // 选择图标
                    $('.icon-grid-item').on('click', function() {
                        var value = $(this).data('value');
                        var select = $(this).closest('.icon-select-wrapper').parent().find('select[name="{0}"]');
                        select.val(value).trigger('change');
                        
                        // 更新预览
                        $(this).closest('.icon-select-wrapper').find('.selected-icon-preview i').attr('class', value);
                        
                        // 隐藏选择器
                        $(this).closest('.icon-select-container').hide();
                    });
                    
                    // 搜索图标
                    $('.icon-search').on('input', function() {
                        var search = $(this).val().toLowerCase();
                        $(this).siblings('.icon-options').find('.icon-grid-item').each(function() {
                            var title = $(this).attr('title').toLowerCase();
                            var value = $(this).data('value').toLowerCase();
                            $(this).toggle(title.indexOf(search) > -1 || value.indexOf(search) > -1);
                        });
                    });
                    
                    // 点击外部关闭选择器
                    $(document).on('click', function(e) {
                        if (!$(e.target).closest('.icon-select-wrapper').length) {
                            $('.icon-select-container').hide();
                        }
                    });
                });
            })(jQuery);
        </script>
        '''.format(name)
        
        return mark_safe(output + js)

admin.site.register(NavigationGroup, NavigationGroupAdmin)
admin.site.register(NavigationLink, NavigationLinkAdmin)
